<template>
  <span>
    <el-popover placement="bottom" title="" width="200" trigger="click">
      <div class="h-item" @click="Announcement">
        <span>集团公告</span>
        <span class="num"
          >（<span class="c-color">{{ msg1Count }}</span
          >）</span
        >
      </div>
      <div class="h-item" @click="Message">
        <span>消息通知</span>
        <span class="num"
          >（<span class="c-color">{{ msg2Count }}</span
          >）</span
        >
      </div>
      <span slot="reference" class="icon-style">
        <i class="el-icon-message-solid"></i>
        <div class="total">{{ msgTotal }}</div>
      </span>
    </el-popover>
  </span>
</template>
  
  <script>
import store from "@/store";
import { getSmallBellTotal } from "@/api/system/notice";

import { mapGetters, mapState } from "vuex";
export default {
  name: "HeaderNotice",
  components: {},
  data() {
    return {
      loadding: false,
      msg1Count: 0,
      msg2Count: 0,
      websock: null,
      lockReconnect: false,
      wsConnectErrorTime: 1,
      heartCheck: null,
    };
  },
  computed: {
    msgTotal() {
      const num = parseInt(this.msg1Count) + parseInt(this.msg2Count);
      return num > 99 ? 99 : num;
    },

    ...mapGetters(["userInfo"]),
  },

  watch: {
    msgTotal: function (val) {
      this.changeMsgTotal(val);
    },

    "$store.state.user.msgTotal": function () {
      this.loadData();
    },
  },
  mounted() {
    this.loadData();
    //this.timerFun();
    this.initWebSocket();
    // this.heartCheckFun();
  },
  destroyed: function () {
    // 离开页面生命周期函数
    this.websocketOnclose();
  },
  methods: {
    changeMsgTotal(val) {
      store.commit("SET_MSGTOTAL", val);
    },
    // 集团公告
    Announcement() {
      this.$router.push({ path: "/system/notice/announcement" });
    },

    // 消息列表
    Message() {
      this.$router.push({ path: "/system/notice/message" });
    },

    loadData: function () {
      getSmallBellTotal().then((res) => {
        const { code, data } = res;

        if (code === 0) {
          this.msg1Count = data.topic;
          this.msg2Count = data.user;
        }
      });
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      let userId = this.userInfo.id;
      let baseUrl = "http://192.168.5.7:48081"; //process.env.VUE_APP_BASE_API;
      let url =
        baseUrl.replace("https://", "wss://").replace("http://", "ws://") +
        "/websocket/" +
        userId;

      this.websock = new WebSocket(url);

      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
    },
    websocketOnopen: function () {
      console.log("WebSocket连接成功");
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误，第%s次", this.wsConnectErrorTime);

      this.wsConnectErrorTime = this.wsConnectErrorTime + 1;
      if (this.wsConnectErrorTime > 5) {
        console.log("WebSocket连接错误超过5次，就不再重新连了！");
        this.lockReconnect = true;
        return;
      }

      this.reconnect();
    },
    websocketOnmessage: function (e) {
      console.log("-----接收消息-------", e.data);
      var data = eval("(" + e.data + ")"); //解析对象

      this.$notify({
        title: data,
        message: h("div", { style: "" }, ""),
      });

      // this.voiceBroadcast(data.msgTxt)
      //   if(data.cmd == "topic"){
      //       //系统通知
      //     this.loadData();
      //   }else if(data.cmd == "user"){
      //       //用户消息
      //     this.loadData();
      //   }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      console.log("connection closed (" + e + ")");
      if (e) {
        console.log("connection closed (" + e.code + ")");
      }
      this.reconnect();
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    //语音播报系统通知
    voiceBroadcast(text) {
      var url =
        "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" +
        encodeURI(text); // baidu文字转语音
      var voiceContent = new Audio(url);
      voiceContent.src = url;
      voiceContent.play();
    },

    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 20000);
    },
    heartCheckFun() {
      var that = this;
      //心跳检测,每20s心跳一次
      that.heartCheck = {
        timeout: 20000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
          clearTimeout(this.timeoutObj);
          //clearTimeout(this.serverTimeoutObj);
          return this;
        },
        start: function () {
          var self = this;
          this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            that.websocketSend("HeartBeat");
            console.info("客户端发送心跳");
            //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
            //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            //}, self.timeout)
          }, this.timeout);
        },
      };
    },
  },
};
</script>
  
  <style lang="scss">
.h-item {
  padding: 10px 0px;
  cursor: pointer;
  .num {
    .c-color {
      color: red;
    }

    float: right;
  }
}

.icon-style {
  position: relative;
  color: #333;
  .total {
    width: 16px;
    height: 16px;
    position: absolute;
    line-height: 16px;
    font-size: 10px;
    text-align: center;
    color: #fff;
    top: -6px;
    right: -6px;
    z-index: 1;
    border-radius: 50%;
    background-color: red;
  }
}
</style>